<?php

class CartController extends Controller
{
 
	public function actionAdd($id, $quantity = null)
	{
        $oOrder = new Order();

        $response = array('success' => true);

        $oOrder->addGoodsToCart($id, ($quantity > 0 ? $quantity : 1), $this->_getParams());

        $response['btn'] = '<a class="btn buy" href="'. Yii::app()->controller->createUrl('/cart/', array()) .'">'. _('Добавлено в корзину') .'</a>';

        if(!$this->_isXmlHttpRequest() && isset($_SERVER['HTTP_REFERER']))
            return $this->redirect($_SERVER['HTTP_REFERER']);

        echo json_encode($response); exit;
	}

	public function actionRemove($id)
	{
        $oOrder = new Order();

        $response = array('success' => true);

        $oOrder->addGoodsToCart($id, 0);

        if(!$this->_isXmlHttpRequest() && isset($_SERVER['HTTP_REFERER']))
            return $this->redirect($_SERVER['HTTP_REFERER']);

        echo json_encode($response); exit;
	}

    public function actionList()
	{
		$toView = array();
        $oGoods = new Goods();
        $oPhotos = new Photos();
        $oOrder = new Order();


        $quantities = $this->_getParam('quantity');
        if($quantities)
        {
            foreach($quantities as $id => $quantity)
                $oOrder->addGoodsToCart($id, ($quantity > 0 ? $quantity : 1), array(), false);

            if($this->_isXmlHttpRequest())
            {}
        }

		$toView['oOrderGoods'] = $aGoodsId = array();
		$oOrderGoods = $oOrder->getInCart();
		foreach($oOrderGoods as $oGoodsRow)
		{
			$toView['oOrderGoods'][$oGoodsRow->goods_id] = $oGoodsRow;
			$aGoodsId[$oGoodsRow->goods_id] = $oGoodsRow->goods_id;
		}

        $oRowset = $oGoods->findAllByPk($aGoodsId);
        $oPhotos->selectMainByRowset($oRowset);

		// Select colors
		$oGoodsProperty = new GoodsProperty();
		$oGoodsProperty->selectByRowset($oRowset, '4');

		// Select sizes
		$oGoodsProperty->selectByRowset($oRowset, '3');

//		print_r($oRowset); exit;

        if($this->_isPost() && isset($_POST['order']))
        {
            $oOrder = new Order();
	        $oOrder = $oOrder->findByPk($oOrder->getOrderId());
            $oOrder->setAttributes(array(
                'name' => String::stripTagsAttributes($this->_getParam('name')),
                'phone' => String::stripTagsAttributes($this->_getParam('phone')),
                'address' => String::stripTagsAttributes($this->_getParam('address')),
                'comment' => String::stripTagsAttributes($this->_getParam('comment')),
                'date' => date('Y-m-d H:i:s'),
                'ip' => (!empty($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : 'не определен'),
                'status' => Order::STATUS_NEW,
            ));

            $oOrder->save();
            $orderId = $oOrder->getPrimaryKey();

            foreach($oRowset as $oRow)
            {
                $oOrderGoods = new OrderGoods();
	            $oOrderGoods = $oOrderGoods->findByAttributes(array(
	                                                'order_id' => $orderId,
	                                                'goods_id' => $oRow->id
	                                           ));

	            if(empty($oOrderGoods))
		            continue;

	            $oOrderGoods->title = $oRow->title;
	            $oOrderGoods->quantity = $oOrder->getCountInCart($oRow->id);
                $oOrderGoods->price = $oRow->price;

                $oOrderGoods->save();
            }

            $oSession = new CHttpSession();
            $oSession->open();
            $oSession['order_id'] = $orderId;
            $oSession['ordered_goods_id'] = $aGoodsId;

            if($orderId > 0)
            {
                $mail = new YiiMailer('order', array(
                    'message' => 'Спасибо за заказ', 'name' => Yii::app()->name, 'description' => 'Заказ № '. $orderId,
                    'oRowset' => $oRowset, 'oOrder' => $oOrder,
                ));
                $mail->setFrom('order@stylepit.ua', Yii::app()->name); //'info@'. Yii::app()->params['host']
                $mail->setTo(Yii::app()->params['adminEmail']);
                $mail->setSubject('Спасибо за ваш заказ. Номер вашего заказа: № '. $orderId);
                $mail->send();

                return $this->redirect(Yii::app()->controller->createUrl('/goods/cart/success', array()));
            }
        }

		// Breadcrumbs
		$this->breadcrumbs['Корзина'] = Yii::app()->createUrl('/cart', array());

		$toView['oRowset'] = $oRowset;

        $this->layout='//layouts/main';
		$this->render('list', $toView);
	}

    public function actionSuccess()
    {
	    $toView = array();

        $oSession = new CHttpSession();
        $oSession->open();

        if(isset($oSession['cart']))
            unset($oSession['cart']);

	    $toView['orderId'] = $orderId = $oSession['order_id'];

	    if(!empty($oSession['ordered_goods_id']))
	    {
            $orderedGoodsId = $oSession['ordered_goods_id'];
		    $oGoods = new Goods();
		    $oPhotos = new Photos();
		    $oGoodsView = new GoodsView();

		    $topIds = $oGoodsView->getViewedGoodsId($orderedGoodsId);
		    if($topIds)
		    {
			    $toView['oGoodsRowset'] = $oGoods->id($topIds)
		                                        ->status(array(1,2))
				                                ->limit(8)
				                                ->orderByRand()
				                                ->findAll();
			    $oPhotos->selectMainByRowset($toView['oGoodsRowset']);
		    }
	    }

        $this->layout='//layouts/main';
        $this->render('success', $toView);
    }

}